/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.jg.report.information.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.thrift.TException;
import org.jeecg.common.constant.enums.ReportPlatformEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.LngLonUtil;
import org.jeecg.modules.api.wlhy.app.bean.ResBaseBean;
import org.jeecg.modules.api.wlhy.app.utils.HttpUtils;
import org.jeecg.modules.third.dongjiang.tax.system.utils.HttpUtil;
import org.jeecg.modules.third.jg.report.information.constant.enums.PaymentMeansCodeEnum;
import org.jeecg.modules.third.jg.report.information.constant.enums.ReportDocTypeEnum;
import org.jeecg.modules.third.jg.report.information.dto.DriverDTO;
import org.jeecg.modules.third.jg.report.information.dto.ReqHeaderDTO;
import org.jeecg.modules.third.jg.report.information.dto.ResultDTO;
import org.jeecg.modules.third.jg.report.information.dto.VehicleDTO;
import org.jeecg.modules.third.jg.report.information.dto.enterprise.AppsDTO;
import org.jeecg.modules.third.jg.report.information.dto.enterprise.EnterpriseDTO;
import org.jeecg.modules.third.jg.report.information.dto.financial.FinancialDTO;
import org.jeecg.modules.third.jg.report.information.dto.financial.FinanciallistDTO;
import org.jeecg.modules.third.jg.report.information.dto.financial.ShippingNoteListDTO;
import org.jeecg.modules.third.jg.report.information.dto.shippingnote.*;
import org.jeecg.modules.third.jg.report.information.thrift.ReportPlatformServiceClient;
import org.jeecg.modules.third.jg.report.information.utils.XmlUtils;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.service.impl.HyCustomerServiceImpl;
import org.jeecg.modules.wlhy.enterprise.entity.HyEnterprise;
import org.jeecg.modules.wlhy.enterprise.entity.HyEnterpriseApps;
import org.jeecg.modules.wlhy.enterprise.service.IHyEnterpriseService;
import org.jeecg.modules.wlhy.enterprise.service.impl.HyEnterpriseAppsServiceImpl;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriverReport;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverReportService;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleReport;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicleType;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleReportService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.service.impl.HyOrderServiceImpl;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.mapper.HyShippingNoteMapper;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 天津省平台上报信息
 *
 * @author duanlikao
 * @created 2021/1/20
 */
@Service
public class ReportInformationService {

    @Resource
    private IHyDriverService driverService;

    @Resource
    private IHyVehicleService vehicleService;

    @Resource
    private  IHyEnterpriseService enterpriseService;
    @Resource
    private HyEnterpriseAppsServiceImpl enterpriseAppsService;

    @Resource
    private HyShippingNoteMapper hyShippingNoteMapper;

    @Resource
    private HyOrderServiceImpl orderService;

    @Resource
    private HyCustomerServiceImpl customerService;
    @Resource
    private IHyShippingNoteService  shippingNoteService;

    @Autowired
    private ReportPlatformServiceClient reportService;

    @Autowired
    private IHyShippingNoteBillService shippingNoteBillService;

    @Autowired
    private IHyCompanyService hyCompanyService;


    @Resource
    private IHyVehicleReportService vehicleReportService;

    @Resource
    private IHyDriverReportService hyDriverReportService;


    private static final Logger LOGGER = LoggerFactory.getLogger(ReportInformationService.class);

    /**
     * thriftClientReport
     * @param reporDocType
     * @param xmlString
     * @return
     * @throws TException
     */
    private  ResultDTO reportPlatform(String reporDocType ,String xmlString) {
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getTjReportIzUse()){
            throw new JeecgBootException("天津上报服务暂未开启,请联系管理。");
        }
//        LOGGER.info("ReportInformationService reportPlatform reporDocType :{} xmlString :{}",reporDocType , xmlString);
            reportPlatformDTO reportPlatformDTO=new reportPlatformDTO();
            reportPlatformDTO.setReporDocType(reporDocType);
            reportPlatformDTO.setXmlString(xmlString);
            String localModeStr = JSONObject.toJSONString(reportPlatformDTO);
            String res = HttpUtils.sendPost("http://172.17.0.1:9021/sendReport", localModeStr);
//            String res = HttpUtils.sendPost("http://127.0.0.1:9021/sendReport", localModeStr);
            ResultDTO resBaseBean = JSONObject.parseObject(res, ResultDTO.class);
            return resBaseBean;
    }


    public static void main(String[] args) {


        reportPlatformDTO reportPlatformDTO=new reportPlatformDTO();
        reportPlatformDTO.setReporDocType("123123");
        reportPlatformDTO.setXmlString("456456");
        String localModeStr = JSONObject.toJSONString(reportPlatformDTO);
        String res = HttpUtils.sendPost("http://127.0.0.1:9021/sendReport1", localModeStr);
        ResultDTO resBaseBean = JSONObject.parseObject(res, ResultDTO.class);
        System.out.println(resBaseBean);
    }

    /**
     * 司机上报
     * @param driverId
     * @return
     */
    public boolean uploadDriver(String driverId){
        HyDriver hyDriverDb = driverService.getById(driverId);
        if(hyDriverDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        HyDriverReport hyDriverReport = new HyDriverReport();
        try {
            //人员从业资格证验证
            if(!driverService.checkQualificationV2(hyDriverDb)){
                throw new JeecgBootException("人员从业资格证验证号不正确或者已过期，请修改后重新上传！");
            }

            String xmlString = "";
            DriverDTO driverDTO = hyDriverTODriverDTO(hyDriverDb );
            if(driverDTO != null){
                ReqHeaderDTO reqHeaderDTO= new ReqHeaderDTO();
                reqHeaderDTO.setDriver(driverDTO);
                xmlString = XmlUtils.converTomXml(reqHeaderDTO);
            }
            String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_JSY.getCode();
            ResultDTO reportResult = reportPlatform(reporDocType,xmlString);

            if(reportResult==null){
                hyDriverReport.setId(driverId);
                hyDriverReport.setDriverId(driverId);
                hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
                hyDriverReport.setDriverUploadStatus("2");
                hyDriverReport.setUploadDate( new Date() );
                hyDriverReport.setDriverReportFailureReason("监管上报系统接口异常,联系管理员检查");
                hyDriverReportService.saveDriverReport(hyDriverReport);
                return false;
            }

            hyDriverReport.setId(driverId);
            hyDriverReport.setDriverId(driverId);
            hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
            hyDriverReport.setDriverUploadStatus(reportResult.getCode().equals("00000") ? "1" : "2");
            hyDriverReport.setUploadDate( new Date() );
            hyDriverReport.setDriverReportFailureReason(reportResult.getErrorMessage());
            return hyDriverReportService.saveDriverReport(hyDriverReport);


        }catch (Exception e){
            hyDriverReport.setId(driverId);
            hyDriverReport.setDriverId(driverId);
            hyDriverReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
            hyDriverReport.setDriverUploadStatus("2");
            hyDriverReport.setUploadDate( new Date() );
            hyDriverReport.setDriverReportFailureReason(e.getMessage());
            hyDriverReportService.saveDriverReport(hyDriverReport);
            throw new JeecgBootException(e.getMessage());
        }

    }

    private static DriverDTO hyDriverTODriverDTO(HyDriver hyDriver) {
        if (hyDriver == null) {
            return null;
        }
        DriverDTO driverDTO = new DriverDTO();
        driverDTO.setDriverName(hyDriver.getDriverName());
        driverDTO.setDrivingLicense(hyDriver.getDrivingLicense());
        driverDTO.setVehicleClass(hyDriver.getVehicleClass());
        driverDTO.setQualificationCertificate(
                StringUtils.isNotEmpty(hyDriver.getQualificationCertificate()) ? hyDriver.getQualificationCertificate() : hyDriver.getDrivingLicense()
        );
        driverDTO.setIssuingOrganizations(hyDriver.getIssuingOrganizations());
        driverDTO.setValidPeriodFrom(
                DateUtils.dateToStringNoBar(hyDriver.getValidPeriodFrom())
        );
        driverDTO.setValidPeriodTo(
                DateUtils.dateToStringNoBar(hyDriver.getValidPeriodTo())
        );
        driverDTO.setTelephone(hyDriver.getTelephone());
        return driverDTO;
    }

    /**
     * 上报车辆
     * @param vehicleId
     * @return
     */
    public boolean uploadVehicle(String vehicleId) {


        HyVehicle hyVehiclDb = vehicleService.getById(vehicleId);
        if(hyVehiclDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        HyVehicleReport hyVehicleReport = new HyVehicleReport();
        try {
            if(StringUtils.isEmpty(hyVehiclDb.getRoadTransportNumber())){
                throw new JeecgBootException("车辆道路运输证不能为空！");
            }
            //车辆道路运输证号 中交检查
            if(!vehicleService.checkRTCNoV2(hyVehiclDb)){
                throw new JeecgBootException("车辆道路运输证号不正确或者已过期，请修改后重新上传！");
            }
            //vehicleService.checkVehicleOwner(hyVehiclDb);
//        vehicleService.checkVehicleNumber(hyVehiclDb);
//        String roadLicense =  vehicleService.checkRTCNoV2(hyVehiclDb);

//        String resLicense = vehicleService.vQueryLicenseV2(hyVehicle);
//
//        if (StringUtils.isEmpty(resLicense)) {
//            throw new JeecgBootException("车辆类型不能为空！");
//        }
//        //转换车辆类型
//        JSONObject jsonObject = JSONObject.parseObject(resLicense);
//        String strResult = jsonObject.get("result").toString();
//        VehicleLicenseVO result = JSON.parseObject(strResult, VehicleLicenseVO.class);
//
//        String vehicleTypeText = StringUtils.isNotEmpty( hyVehiclDb.getVehicleType()) ?  hyVehiclDb.getVehicleType() : result.getVclTpNm();

            HyVehicleType hyVehicleType = vehicleService.getHyVehicleType(hyVehiclDb.getVehicleType());
            if(hyVehicleType == null ){
                throw new JeecgBootException("车辆类型不存在,请修改后重新上传！");
            }
            hyVehiclDb.setVehicleType(hyVehicleType.getValue());

            String xmlString = "";
            VehicleDTO vehicleDTO = vehicleDTOTODriverDTO(hyVehiclDb);
            if(vehicleDTO != null){
                ReqHeaderDTO reqHeaderDTO= new ReqHeaderDTO();
                reqHeaderDTO.setVehicle(vehicleDTO);
                xmlString = XmlUtils.converTomXml(reqHeaderDTO);
            }
            String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_CL.getCode();
            ResultDTO reportResult = reportPlatform(reporDocType,xmlString);

            if(reportResult==null){
                hyVehicleReport.setId(vehicleId);
                hyVehicleReport.setVehicleId(vehicleId);
                hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
                hyVehicleReport.setVehicleUploadStatus("2");
                hyVehicleReport.setUploadDate( new Date() );
                hyVehicleReport.setVehicleReportFailureReason("监管上报系统接口异常,联系管理员检查");
                vehicleReportService.saveVehicleReport(hyVehicleReport);
                return  false;
            }

            hyVehicleReport.setId(vehicleId);
            hyVehicleReport.setVehicleId(vehicleId);
            hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
            hyVehicleReport.setVehicleUploadStatus(reportResult.getCode().equals("00000") ? "1" : "2");
            hyVehicleReport.setUploadDate( new Date() );
            hyVehicleReport.setVehicleReportFailureReason(reportResult.getErrorMessage());
            return  vehicleReportService.saveVehicleReport(hyVehicleReport);
        }catch (Exception e){
            hyVehicleReport.setId(vehicleId);
            hyVehicleReport.setVehicleId(vehicleId);
            hyVehicleReport.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
            hyVehicleReport.setVehicleUploadStatus( "2");
            hyVehicleReport.setUploadDate( new Date() );
            hyVehicleReport.setVehicleReportFailureReason(e.getMessage());
            vehicleReportService.saveVehicleReport(hyVehicleReport);
            throw new JeecgBootException(e.getMessage());
        }

    }
    private static VehicleDTO vehicleDTOTODriverDTO(HyVehicle hyVehicle) {
        if (hyVehicle == null) {
            return null;
        }
        VehicleDTO vehicleDTO = new VehicleDTO();
        vehicleDTO.setVehicleNumber(hyVehicle.getVehicleNumber());
        vehicleDTO.setVehiclePlateColorCode(hyVehicle.getVehiclePlateColorCode());
        vehicleDTO.setVehicleType(hyVehicle.getVehicleType());
        vehicleDTO.setOwner(hyVehicle.getOwner());
        vehicleDTO.setUseCharacter(hyVehicle.getUseCharacter());
        vehicleDTO.setVin(hyVehicle.getVin());
        vehicleDTO.setIssuingOrganizations(hyVehicle.getIssuingOrganizations());
        vehicleDTO.setRegisterDate(DateUtils.dateToStringNoBar(hyVehicle.getRegisterDate()));
        vehicleDTO.setIssueDate(DateUtils.dateToStringNoBar(hyVehicle.getIssueDate()));
        vehicleDTO.setVehicleEnergyType(hyVehicle.getVehicleEnergyType());
        vehicleDTO.setVehicleTonnage(
                hyVehicle.getVehicleTonnage() != null ?  hyVehicle.getVehicleTonnage()
                        .setScale(2, BigDecimal.ROUND_DOWN).toString() :"40.00"
        );
        vehicleDTO.setGrossMass(
                hyVehicle.getGrossMass() != null ?  hyVehicle.getGrossMass()
                        .setScale(2,BigDecimal.ROUND_DOWN).toString() : "48.00"
        );
        vehicleDTO.setRoadTransportCertificateNumber(hyVehicle.getRoadTransportNumber());

        return vehicleDTO;
    }

    /**
     * 天津省平台上报企业信息
     * @param actionType 操作类型  1:新增操作 2：更新操作
     * @return
     */
    public ResultDTO uploadEnterprise(String actionType) {
        HyEnterprise hyEnterprise = enterpriseService.queryTopData();
        String xmlString = "";
        EnterpriseDTO enterpriseDTO = enterpriseTOEnterpriseDTO(hyEnterprise,actionType);
        if(enterpriseDTO != null){
            List <AppsDTO> apps = new ArrayList <>();
            QueryWrapper <HyEnterpriseApps> queryWrapper = new QueryWrapper();
            queryWrapper.eq("iz_used",1);
            List <HyEnterpriseApps> enterpriseApps = enterpriseAppsService.list(queryWrapper);
            if(CollectionUtils.isNotEmpty(enterpriseApps)){
                for(HyEnterpriseApps enterpriseApp : enterpriseApps){
                    AppsDTO appsDTO = new AppsDTO();
                    appsDTO.setAppId(enterpriseApp.getAppId());
                    appsDTO.setAppName(enterpriseApp.getAppName());
                    appsDTO.setAppSecurity(enterpriseApp.getAppSecurity());
                    appsDTO.setAppType(enterpriseApp.getAppType());
                    apps.add(appsDTO);
                }
            }
            enterpriseDTO.setApps(apps);
            ReqHeaderDTO reqHeaderDTO= new ReqHeaderDTO();
            reqHeaderDTO.setEnterprise(enterpriseDTO);
            xmlString = XmlUtils.converTomXml(reqHeaderDTO);
        }
        String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_QY.getCode();
        return reportPlatform(reporDocType,xmlString);

    }

    private static EnterpriseDTO enterpriseTOEnterpriseDTO(HyEnterprise hyEnterprise,String actionType) {
        if (hyEnterprise == null) {
            return null;
        }
        EnterpriseDTO enterpriseDTO = new EnterpriseDTO();
        //操作类型  1:新增操作 2：更新操作
        enterpriseDTO.setActionType(actionType);
        enterpriseDTO.setEntName(hyEnterprise.getEntName());
        enterpriseDTO.setUnifiedSocialCreditIdentifier(hyEnterprise.getUnifiedSocialCreditIdentifier());
        enterpriseDTO.setEntAddress(hyEnterprise.getEntAddress());
        enterpriseDTO.setAreaCode(hyEnterprise.getAreaCode());
        enterpriseDTO.setRegisterMoney(hyEnterprise.getRegisterMoney());
        enterpriseDTO.setRegisterDate(
                DateUtils.dateToStringNoBar(hyEnterprise.getRegisterDate())
        );
        enterpriseDTO.setRunScope(hyEnterprise.getRunScope());
        enterpriseDTO.setPermitNumber(hyEnterprise.getPermitNumber());
        enterpriseDTO.setFaxNo(hyEnterprise.getFaxNo());
        enterpriseDTO.setLegalerName(hyEnterprise.getLegalerName());
        enterpriseDTO.setLegalerTel(hyEnterprise.getLegalerTel());
        enterpriseDTO.setContactsName(hyEnterprise.getContactsName());
        enterpriseDTO.setContactsTel(hyEnterprise.getContactsTel());
        //监测状态  监测状态：0：未开启；1：联调测试开启；2：正式监测开启
        enterpriseDTO.setMonitorsState(hyEnterprise.getMonitorsState());
        enterpriseDTO.setMonitorTime(
                DateUtils.dateToStringDateTime(hyEnterprise.getMonitorTime())
        );
        enterpriseDTO.setEnterpriseCreateTime(
                DateUtils.dateToStringNoBar(hyEnterprise.getEnterpriseCreateTime())
        );
        enterpriseDTO.setIpcNum(hyEnterprise.getIpcnum());
        enterpriseDTO.setPsnrnum(hyEnterprise.getPsnrnum());
        return enterpriseDTO;
    }

    /**
     * 天津省平台上报电子运单
     * @param hyShippingNote
     * @return
     */
    public ResultDTO uploadShippingNote(HyShippingNote hyShippingNote) {
        HyShippingNote ShippingNoteDb = shippingNoteService.getById(hyShippingNote.getId());
        if(ShippingNoteDb == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        /*if("1".equals(ShippingNoteDb.getUploadStatus())){
            return true;
        }*/
        try{
//            if(!"2".equals(hyShippingNote.getUploadStatus())) {
//                HyVehicle hyVehicle = vehicleService.getById(hyShippingNote.getVehicleId());
//                if(hyVehicle.getVehicleType().contains("重型")){
//                    String startTime = DateUtils.dateTimeToString(hyShippingNote.getStatusDtReceive());
//                    String endTime = DateUtils.dateTimeToString(hyShippingNote.getStatusDtUnloading());
//                    WaybillRouteVO waybillRouteVO = shippingNoteService.getWaybillRoute(hyVehicle.getVehicleNumber(), startTime, endTime, "GCJ02");
//                    if (waybillRouteVO == null || CollectionUtils.isEmpty(waybillRouteVO.getPointDataList())) {
//                        throw new JeecgBootException("该运单没有运单轨迹！");
//                    }
//                }
//
//            }
            HyVehicle hyVehicle = vehicleService.getById(hyShippingNote.getVehicleId());
            if(hyVehicle == null){
                throw new JeecgBootException("该运单车辆信息不能为空");
            }
            if(hyShippingNote.getGoodsWeightLoading().compareTo(hyVehicle.getVehicleTonnage()) > 0 ){
                hyShippingNote.setUploadStatus("2");
                hyShippingNote.setUploadDate(new Date());
                hyShippingNote.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
                hyShippingNote.setReportFailureReason("货物质量超过车辆核定载质量货物质量:"+hyShippingNote.getGoodsWeightLoading()+"车辆核定载质量:"+hyVehicle.getVehicleTonnage());
                shippingNoteService.updateById(hyShippingNote);
                throw new JeecgBootException("货物质量超过车辆核定载质量货物质量:"+hyShippingNote.getGoodsWeightLoading()+"车辆核定载质量:"+hyVehicle.getVehicleTonnage());
            }

            ShippingNoteDb.setCompanyId(hyShippingNote.getCompanyId());
            String xmlString = "";
            ShippingNoteDTO shippingNoteDTO = shippingNoteTOShippingNoteDTO(ShippingNoteDb);
            if(shippingNoteDTO != null){
                ReqHeaderDTO reqHeaderDTO= new ReqHeaderDTO();
                reqHeaderDTO.setShippingNote(shippingNoteDTO);
                xmlString = XmlUtils.converTomXml(reqHeaderDTO);
            }
            String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_YD.getCode();
            ResultDTO reportResult = reportPlatform(reporDocType,xmlString);

            if(reportResult==null){
                hyShippingNote.setUploadStatus("2");
                hyShippingNote.setUploadDate(new Date());
                hyShippingNote.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
                hyShippingNote.setReportFailureReason("监管上报系统接口异常,联系管理员检查");
                shippingNoteService.updateById(hyShippingNote);
                return reportResult;
            }

            if(reportResult.getErrorMessage().equals("车辆信息未上报")){
                this.uploadVehicle(hyShippingNote.getVehicleId());
//                this.uploadShippingNote(hyShippingNote);
            }
            if(reportResult.getErrorMessage().equals("驾驶员信息未上报")){
                this.uploadDriver(hyShippingNote.getDriverId());
//                this.uploadShippingNote(hyShippingNote);
            }


            hyShippingNote.setUploadStatus(reportResult.getCode().equals("00000") ? "1" : "2");
            hyShippingNote.setUploadDate(new Date());
            hyShippingNote.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
            hyShippingNote.setReportFailureReason(reportResult.getErrorMessage());
            shippingNoteService.updateById(hyShippingNote);
            return reportResult ;
        }catch (Exception e){
            hyShippingNote.setUploadStatus("2");
            hyShippingNote.setReportFailureReason(e.getMessage());
            hyShippingNote.setUploadDate(new Date());
            hyShippingNote.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
            shippingNoteService.updateById(hyShippingNote);
            throw new JeecgBootException(e.getMessage());
        }
    }

    /**
     * 组装电子运单报文
     * @param hyShippingNote
     * @return
     */
    private  ShippingNoteDTO shippingNoteTOShippingNoteDTO(HyShippingNote hyShippingNote) {
        if (hyShippingNote == null) {
            throw new JeecgBootException("该运单上报数据不能为空");
        }

        HyCustomer hyCustomer = customerService.getById(hyShippingNote.getCustomerId());
        if(hyCustomer == null){
            throw new JeecgBootException("该运单货主信息不能为空");
        }

        HyOrder hyOrder = orderService.getById(hyShippingNote.getOrderId());
        if(hyOrder == null){
            throw new JeecgBootException("该运单货源信息不能为空");
        }

        HyDriver hyDriver = driverService.getById(hyShippingNote.getDriverId());
        if(hyDriver == null){
            throw new JeecgBootException("该运单司机信息不能为空");
        }
        HyVehicle hyVehicle = vehicleService.getById(hyShippingNote.getVehicleId());
        if(hyVehicle == null){
            throw new JeecgBootException("该运单车辆信息不能为空");
        }

//        //申报公司：河北一六八网络科技有限公司天津第二分公司

        HyCompany company = hyCompanyService.getById(hyShippingNote.getCompanyId());
        if(company == null){
            throw new JeecgBootException("该运单公司信息不能为空");
        }



        ShippingNoteDTO shippingNoteDTO = new ShippingNoteDTO();

        shippingNoteDTO.setOriginalDocumentNumber(hyOrder.getOrderNum());
        String shippingNoteNumber = hyShippingNote.getShippingNoteNumber().replaceAll("-","");
        if(shippingNoteNumber.length() > 20 ){
            shippingNoteNumber =  shippingNoteNumber.substring(0, 20);
        }
        shippingNoteDTO.setShippingNoteNumber(shippingNoteNumber);

        //Integer vehicleAmounthy = getVehicleAmounthyByOrderId(hyShippingNote.getOrderId()) ;
        shippingNoteDTO.setVehicleAmount(1);
        //分段分单号 分段运输和多车运输由 四位数字组成， 前两位代表一 单多车的序号，后两位代表分 段序号。
        //若运输形式为一单一 车填 0000。
        shippingNoteDTO.setSerialNumber("0000");
        //运输组织类型代码
        shippingNoteDTO.setTransportTypeCode(1);
        shippingNoteDTO.setSendToProDateTime(
                DateUtils.dateToStringDateTime(new Date())
        );

        shippingNoteDTO.setCarrier(company.getCompanyName());
        shippingNoteDTO.setUnifiedSocialCreditIdentifier(company.getCreditCode());
        //道路运输经营许可证编号 车辆道路运输经营许可 网络货运经营者的 道路运输经营许可证编号。
        shippingNoteDTO.setPermitNumber(company.getPermitNumber());
        shippingNoteDTO.setConsignmentDateTime(
                DateUtils.dateToStringDateTime(hyShippingNote.getCreateTime())
        );
        shippingNoteDTO.setBusinessTypeCode(hyShippingNote.getBusinessTypeCode());

        shippingNoteDTO.setDespatchActualDateTime(
                DateUtils.dateToStringDateTime(hyShippingNote.getStatusDtLoading())
        );
        shippingNoteDTO.setGoodsReceiptDateTime(
                DateUtils.dateToStringDateTime(hyShippingNote.getStatusDtUnloading())
        );
        BigDecimal costPayShipping = hyShippingNote.getDriverFee() ;


        shippingNoteDTO.setTotalMonetaryAmount(
                costPayShipping.setScale(3, BigDecimal.ROUND_DOWN).toString()
        );
//        BigDecimal costPayShipping = hyShippingNote.getCostPayShipping() ;
        //是否使用油气 和 是否充值成功
//        if(hyShippingNote.getIzUsedGas().equals("1") && hyShippingNote.getGasStatus().equals("2")){
//            costPayShipping = hyShippingNote.getGasAmount();
//        }

        BigDecimal gasAmount = BigDecimal.ZERO;
        if(!"0".equals(hyShippingNote.getIzUsedGas())) {
            gasAmount = hyShippingNote.getGasRechargeAmount();
        }

        shippingNoteDTO.setTransportationCost(
                gasAmount.setScale(3, BigDecimal.ROUND_DOWN).toString()
        );
        double m =  LngLonUtil.GetDistance( hyShippingNote.getSendLatitude(), hyShippingNote.getSendLongitude(),
                hyShippingNote.getReceiveLatitude(),hyShippingNote.getReceiveLongitude());
        double km =  m > 0d ? Math.round((m/100d)/10d) : 0d;
        shippingNoteDTO.setTransportationDistance(
               StringUtils.isNotEmpty(hyShippingNote.getTransportationDistance()) ? hyShippingNote.getTransportationDistance() : String.valueOf((int)Math.round(km))
        );

        shippingNoteDTO.setFinishDateTime(
                DateUtils.dateToStringDateTime(hyShippingNote.getPayDt())
        );

        //托运人信息
        getConsignorInfo(hyCustomer, hyShippingNote, shippingNoteDTO);
        //收货方信息
        getConsigneeInfo(hyShippingNote, shippingNoteDTO);
        //车辆信息
        getVehicleInfo(hyShippingNote,  hyDriver, hyVehicle, shippingNoteDTO);
        //实际承运人信息
        getActualCarrierInfo(hyVehicle,hyDriver,  shippingNoteDTO);
        //保险信息
        getInsuranceInformation(shippingNoteDTO);

        return shippingNoteDTO;
    }

    /**
     * 保险信息
     * @param shippingNoteDTO
     */
    private void getInsuranceInformation(ShippingNoteDTO shippingNoteDTO) {
        InsuranceInformation insuranceInformation = new InsuranceInformation();
        insuranceInformation.setInsuranceCompanyCode("none");
        insuranceInformation.setPolicyNumber("none");
        shippingNoteDTO.setInsuranceInformation(insuranceInformation);
    }

    /**
     * 实际承运人信息
     * @param hyVehicle
     * @param hyDriver
     * @param shippingNoteDTO
     */
    private void getActualCarrierInfo(HyVehicle hyVehicle,HyDriver hyDriver,  ShippingNoteDTO shippingNoteDTO) {
        ActualCarrierInfo actualCarrierInfo = new ActualCarrierInfo();
        actualCarrierInfo.setActualCarrierName(hyDriver.getDriverName());
        actualCarrierInfo.setActualCarrierBusinessLicense(
                StringUtils.isNotBlank(hyVehicle.getBusinessLicense()) ? hyVehicle.getBusinessLicense() :
                        hyVehicle.getRoadTransportNumber().substring(0 , 6) +"000000"
                //hyVehicle.getRoadTransportNumber()
        );
        actualCarrierInfo.setActualCarrierId(hyDriver.getIdcard());
        shippingNoteDTO.setActualCarrierInfo(actualCarrierInfo);
    }

    /**
     * 车辆信息
     * @param hyShippingNote
     * @param hyDriver
     * @param hyVehicle
     * @param shippingNoteDTO
     */
    private void getVehicleInfo(HyShippingNote hyShippingNote,  HyDriver hyDriver, HyVehicle hyVehicle,
            ShippingNoteDTO shippingNoteDTO) {
        VehicleInfo vehicleInfo = new VehicleInfo();
        vehicleInfo.setVehiclePlateColorCode(hyVehicle.getVehiclePlateColorCode());
        vehicleInfo.setVehicleNumber(hyVehicle.getVehicleNumber());
        vehicleInfo.setDespatchActualDateTime(
                DateUtils.dateToStringDateTime( hyShippingNote.getStatusDtLoading())
        );
        vehicleInfo.setGoodsReceiptDateTime(
                DateUtils.dateToStringDateTime( hyShippingNote.getStatusDtUnloading())
        );
        vehicleInfo.setPlaceOfLoading(hyShippingNote.getSendAddress());
        vehicleInfo.setGoodsReceiptPlace(hyShippingNote.getReceiveAddress());
        vehicleInfo.setLoadingCountrySubdivisionCode(hyShippingNote.getSendAreaCode());
        vehicleInfo.setReceiptCountrySubdivisionCode(hyShippingNote.getReceiveAreaCode());
        //司机信息
        getDrivers(hyDriver, vehicleInfo);
        //货物信息
        getGoodsInfos(hyShippingNote, vehicleInfo);
        shippingNoteDTO.setVehicleInfo(vehicleInfo);
    }

    /**
     * 货物信息
     * @param hyShippingNote
     * @param vehicleInfo
     */
    private void getGoodsInfos( HyShippingNote hyShippingNote ,VehicleInfo vehicleInfo) {
        List <GoodsInfo> goodsInfos = new ArrayList <>();
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setDescriptionOfGoods(hyShippingNote.getDescriptionOfGoods());
        goodsInfo.setCargoTypeClassificationCode(hyShippingNote.getCargoTypeClassificationCode());
        BigDecimal  goodsWeightLoading =  hyShippingNote.getGoodsWeightLoading().multiply(new BigDecimal("1000"));
        goodsInfo.setGoodsItemGrossWeight(
                goodsWeightLoading.setScale(3, BigDecimal.ROUND_DOWN)
                        .toString()
        );
        goodsInfo.setCube("1.0000");
        goodsInfo.setTotalNumberOfPackages(1);
        goodsInfos.add(goodsInfo);
        vehicleInfo.setGoodsInfo(goodsInfos);
    }

    /**
     * 司机信息
     * @param hyDriver
     * @param vehicleInfo
     */
    private void getDrivers(HyDriver hyDriver, VehicleInfo vehicleInfo) {
        List <DriverDTO> drivers = new ArrayList <>();
        DriverDTO driverDTO= new  DriverDTO();
        driverDTO.setDriverName(hyDriver.getDriverName());
        driverDTO.setDrivingLicense(hyDriver.getDrivingLicense());
        drivers.add(driverDTO);
        vehicleInfo.setDriver(drivers);
    }

    /**
     * 收货方信息
     * @param hyShippingNote
     * @param shippingNoteDTO
     */
    private void getConsigneeInfo(HyShippingNote hyShippingNote, ShippingNoteDTO shippingNoteDTO) {
        ConsigneeInfo consigneeInfo = new ConsigneeInfo();
        consigneeInfo.setConsignee(hyShippingNote.getReceiveContactName());
        consigneeInfo.setConsigneeId("");
        consigneeInfo.setGoodsReceiptPlace(hyShippingNote.getReceiveAddress());
        consigneeInfo.setCountrySubdivisionCode(hyShippingNote.getReceiveAreaCode());
        shippingNoteDTO.setConsigneeInfo(consigneeInfo);
    }

    /**
     * 托运人信息
     * @param hyCustomer
     * @param hyShippingNote
     * @param shippingNoteDTO
     */
    private void getConsignorInfo(HyCustomer hyCustomer, HyShippingNote hyShippingNote, ShippingNoteDTO shippingNoteDTO) {
        ConsignorInfo consignorInfo = new ConsignorInfo();
        consignorInfo.setConsignor(hyCustomer.getCustomerName());
        consignorInfo.setConsignorID( StringUtils.isNotBlank(hyCustomer.getCreditCode()) ? hyCustomer.getCreditCode() : hyCustomer.getIdcard());
        consignorInfo.setPlaceOfLoading(hyShippingNote.getSendAddress());
        consignorInfo.setCountrySubdivisionCode(hyShippingNote.getSendAreaCode());
        shippingNoteDTO.setConsignorInfo(consignorInfo);
    }

    /**
     * 根据货源ID有效查询运单数
     * @param orderId
     * @return
     */
    public int getVehicleAmounthyByOrderId(String orderId){
        return hyShippingNoteMapper.getVehicleAmounthyByOrderId(orderId);
    }

    /**
     * 天津运单资金流水单上报
     */
    public ResultDTO uploadCapitalFlow(String shippingId){


        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("shipping_id", shippingId);

        List<HyShippingNoteBill> shippingNoteBills = shippingNoteBillService.list(queryWrapper);
        if(CollectionUtils.isEmpty(shippingNoteBills)) {
            throw new JeecgBootException("未找到对应数据");
        }
        for(HyShippingNoteBill shippingNoteBill:shippingNoteBills){
            if("1".equals(shippingNoteBill.getUploadStatus())){
                throw new JeecgBootException("请不要重复上传数据");
            }
        }

        HyShippingNote hyShippingNote = shippingNoteService.getById(shippingId);
        FinancialDTO financialDTO = getFinancialDTO(shippingNoteBills,hyShippingNote);
        String xmlString = "";
        if(financialDTO != null){
            ReqHeaderDTO reqHeaderDTO= new ReqHeaderDTO();
            reqHeaderDTO.setFinancial(financialDTO);
            xmlString = XmlUtils.converTomXml(reqHeaderDTO);
        }
        String reporDocType = ReportDocTypeEnum.REPORT_DOC_TYPE_WLHY_ZJ.getCode();
        ResultDTO reportResult = reportPlatform(reporDocType,xmlString);
        if(reportResult==null){
            for(HyShippingNoteBill shippingNoteBill:shippingNoteBills){
                shippingNoteBill.setUploadStatus("2");
                shippingNoteBill.setUploadDate(new Date());
                shippingNoteBill.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
                shippingNoteBill.setReportFailureReason("监管上报系统接口异常,请联系管理员");
            }
            shippingNoteBillService.updateBatchById(shippingNoteBills);
        }
        for(HyShippingNoteBill shippingNoteBill:shippingNoteBills){
            shippingNoteBill.setUploadStatus(reportResult.getCode().equals("00000") ?"1" :"2");
            shippingNoteBill.setUploadDate(new Date());
            shippingNoteBill.setReportPlatformType(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode());
            shippingNoteBill.setReportFailureReason(reportResult.getErrorMessage());
        }
        shippingNoteBillService.updateBatchById(shippingNoteBills);

        return reportResult ;
    }

    private static FinancialDTO getFinancialDTO(List<HyShippingNoteBill> shippingNoteBills,HyShippingNote hyShippingNote) {
        FinancialDTO financialDTO = new FinancialDTO();
        HyShippingNoteBill  shippingNoteBillDb = shippingNoteBills.get(0);



        financialDTO.setDocumentNumber(shippingNoteBillDb.getBillNum());
        financialDTO.setSendToProDateTime(
                DateUtils.dateToStringDateTime(new Date())
        );
        financialDTO.setCarrier(shippingNoteBillDb.getCarrier());
        financialDTO.setActualCarrierId(shippingNoteBillDb.getActualCarrierId());
        financialDTO.setVehicleNumber(shippingNoteBillDb.getVehicleNumber());
        financialDTO.setVehiclePlateColorCode(shippingNoteBillDb.getVehicleColorCode());

        //运单列表
        List <ShippingNoteListDTO> shippingNoteListDTOS = new ArrayList <>();
        ShippingNoteListDTO shippingNoteListDTO = new ShippingNoteListDTO();

        String shippingNoteNumber = shippingNoteBillDb.getShippingNoteNumber().replaceAll("-","");
        if(shippingNoteNumber.length() > 20 ){
            shippingNoteNumber =  shippingNoteNumber.substring(0, 20);
        }
        shippingNoteListDTO.setShippingNoteNumber(shippingNoteNumber);
        shippingNoteListDTO.setSerialNumber("0000");
        BigDecimal costPayShipping = hyShippingNote.getDriverFee() ;

        shippingNoteListDTO.setTotalMonetaryAmount(
                costPayShipping.setScale(3, BigDecimal.ROUND_DOWN).toString()
        );

        shippingNoteListDTOS.add(shippingNoteListDTO);
        financialDTO.setShippingNoteList(shippingNoteListDTOS);
        //财务列表
        List<FinanciallistDTO>  financiallistDTOS = new ArrayList <>();
        for(HyShippingNoteBill shippingNoteBill : shippingNoteBills){
            FinanciallistDTO financiallistDTO = new FinanciallistDTO();

            financiallistDTO.setPaymentMeansCode(
                    PaymentMeansCodeEnum.PAYMENT_MEANS_TYPE_YHZZ.code
            );
            financiallistDTO.setRecipient(shippingNoteBill.getCarrier());
            financiallistDTO.setReceiptAccount(
                    shippingNoteBill.getCraccno()+shippingNoteBill.getCrlogaccno()
            );
            financiallistDTO.setBankCode(shippingNoteBill.getBankCode());
            financiallistDTO.setSequenceCode(shippingNoteBill.getBillNum());
            financiallistDTO.setMonetaryAmount(
                    shippingNoteBill.getAmt().setScale(3, BigDecimal.ROUND_DOWN).toString()
            );
            financiallistDTO.setDateTime(
                    DateUtils.dateToStringDateTime(shippingNoteBill.getPayDt())
            );

            financiallistDTOS.add(financiallistDTO);
        }

        financialDTO.setFinanciallist(financiallistDTOS);
        return financialDTO;
    }


}
